package com.ocom.common.entity.typehandler;

import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.sm.SM4Util;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class SignOrderHandle extends BaseTypeHandler<String> {


	private static String key = "0944630BEE5AEA1E6F9F31994186597E" ;

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
		if (StringUtils.isNotBlank(parameter)) {
			ps.setString(i, encrypt(parameter));
		} else {
			ps.setString(i, "");
		}
	}

	@Override
	public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
		String columnValue = decrypt(rs.getString(columnName));
		return columnValue;
	}

	@Override
	public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		String columnValue = rs.getString(columnIndex);
		return decrypt(columnValue);
	}

	@Override
	public String getNullableResult(CallableStatement cs, int columnIndex)
			throws SQLException {
		String columnValue = cs.getString(columnIndex);
		return decrypt(columnValue);
	}

	private String encrypt(String parameter) {
		return encryptS(parameter);
	}

	public String decrypt(String parameter) {
		return decryptS(parameter);
	}

	public static String decryptS(String parameter) {
		if(CommonUtil.isNull(parameter)) return parameter;
		String value = parameter;
		try {
			value = SM4Util.decryptEcb(key, parameter);
			return value;
//			value = DESUtils.decrypt(parameter,"d8a23c004318800604500c495820653a");
		} catch (Exception e) {
//			e.printStackTrace();
		}
		return parameter;
	}

	public static String encryptS(String parameter) {
		if(CommonUtil.isNull(parameter)) return parameter;
		String value = parameter;
		try {
			value = SM4Util.encryptEcb(key, parameter);
			return value;
//			value = DESUtils.encrypt(parameter,"d8a23c004318800604500c495820653a");
		} catch (Exception e) {
//			e.printStackTrace();
		}
		return parameter;
	}







}

